import { Form, Drawer, Input, Select, Upload, Button, message, Icon } from 'antd';
import React from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import styles from './hotQuestion.css';
import { fetchAddLabel, fetchLabelInfoById, fetchEditLabel } from '@/services/hotQuestion';
import top from '@/assets/overview/1.png';
import bottom from '@/assets/overview/2.png';
import close from '@/assets/overview/4.png';
import RelatedKnowledgeV2 from '@/utils/RelatedKnowledgeV2';

class EditModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      imgUrl: '',
      imgName: '',
      questions: [],
      userTypeChecks: ['all'],
      submitLoading: false,
      detail: null,
      isImgOk: true,
      defaultImgUrl: [
        { id: 'U01', url: '/preSetImg/directory.png' },
        { id: 'U02', url: '/preSetImg/game.png' },
        { id: 'U03', url: '/preSetImg/information.png' },
        { id: 'U04', url: '/preSetImg/inspiration.png' },
        { id: 'U05', url: '/preSetImg/lineGraph.png' },
        { id: 'U06', url: '/preSetImg/opinion.png' },
        { id: 'U07', url: '/preSetImg/tag.png' },
        { id: 'U08', url: '/preSetImg/target.png' },
        { id: 'U09', url: '/preSetImg/text.png' },
        { id: 'U10', url: '/preSetImg/time.png' },
      ]
    };
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  initOpen = row => {
    this.setState({ visible: true, detail: row }, () => {
      if (row) {
        this.getLabelDetail();
      }
    });
  };

  /* 获取标签详情 */
  getLabelDetail = async () => {
    const { detail } = this.state;
    const { applicationId } = this.props;
    const res = await fetchLabelInfoById({ id: detail.id });
    const hotQuestion = [];
    /* 处理热点问题 */
    for (const item of res.hotQuestionList) {
      hotQuestion.push({ id: item.qaId, basicQuestion: item.question, type: item.qaType });
    }

    const userTypeList = res.userTypeList ? res.userTypeList.map(item => item.userTypeId) : [];
    if (userTypeList.length === 0) {
      userTypeList.push('all');
    };
    this.props.form.setFieldsValue({
      labelName: res.name,
      userType: userTypeList,
      img: res.imgUrl
    });
    this.setState({
      userTypeChecks: userTypeList,
      imgUrl: res.imgUrl,
      imgName: res.imgName,
      questions: hotQuestion,
    });
  };

  /* 上传图片之前 */
  beforeUpload = file => {
    let b = /\.(png|jpg|jpeg|gif|bmp|tif|ico|webp)$/;
    let a = file.name.toLowerCase();

    const pig = b.test(a);
    const isJPG = file.type;
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!pig) {
      if (!isLt2M) {
        message.error(formatMessage({ id: 'hotSpots.editModal.pleaseUploadImageLessThan2M' }));
      } else {
        message.error(formatMessage({ id: 'hotSpots.editModal.pleaseUploadImageFormat' }));
      };
    } else {
      if (!isLt2M) {
        message.error('请上传小于2M的图片');
      };
    };
    return isJPG && isLt2M && pig;
  };

  /* 修改上传图片 */
  handleChangeImage = info => {
    if (info.file.status === 'done') {
      this.setState({
        imgUrl: info.file.response.url ? info.file.response.url : '',
        imgName: info.file.response.original ? info.file.response.original : '',
        isImgOk: true
      });
    }
  };

  /* 打开热门问题 */
  addHotQuestion = () => {
    const { questions } = this.state;
    console.log(questions);
    this.RelatedKnowledge.openAndInit(questions)
  };

  /* 添加热门问题 */
  addQuestionByHot = (questions) => {
    if (questions.length === 30) {
      message.info(formatMessage({ id: 'hotSpots.editModal.max30HotQuestions' }));
      return false;
    };
    this.setState({ questions });
  };

  /* 取消选中热门问题 */
  removeRelatedQus = (question) => {
    let { questions } = this.state;
    const newQuestions = questions.filter(item => item.id != question.id)
    this.setState({ questions: newQuestions })
  }

  /* 移除热门问题 */
  removeQuestion = (question,index) => {
    let { questions } = this.state;
    let newQuestions = []
    if(question.id == '' && question.type == -1){
      newQuestions = questions.filter((item,i) => i != index);
    }else{
      newQuestions = questions.filter(item => item.id != question.id);
    }
    
    this.setState({ questions: newQuestions });
  };

  /* 上移/下移热门问题 */
  moveQuestion = (index, type) => {
    let { questions } = this.state;
    let newQuestions = [];
    switch (type) {
      case 'up':
        newQuestions = this.swapArray(questions, index - 1, index);
        break;
      case 'down':
        newQuestions = this.swapArray(questions, index, index + 1);
        break;
    }
    this.setState({ questions: newQuestions });
  };

  /* 数组上移下移 */
  swapArray = (arr, index1, index2) => {
    arr[index1] = arr.splice(index2, 1, arr[index1])[0];
    return arr;
  };

  /* 关闭弹窗 */
  cancelModal = () => {
    this.props.form.resetFields();
    this.setState({
      visible: false,
      imgUrl: '',
      imgName: '',
      questions: [],
      userTypeChecks: ['all'],
      submitLoading: false,
      detail: null,
      isImgOk: true
    });
  };

  /* 选择用户类型 */
  changeUserType = value => {
    let { userTypeChecks } = this.state;
    //选择了其他的用户类型 又选择了全部类型 则需要删掉其他的用户类型 只保留全部类型
    if (value === 'all') {
      this.props.form.setFieldsValue({ userType: ['all'] });
      userTypeChecks = ['all'];
    } else {
      userTypeChecks.push(value);
    }
    this.setState({ userTypeChecks });
  };

  /* 去掉用户类型的选择 */
  deselectUserType = value => {
    if (value === 'all') {
      this.setState({ userTypeChecks: [] });
    }
  };

  /* 保存/编辑标签基础信息前校验 */
  doSubmitForm = () => {
    const that = this;
    const { imgUrl, imgName, questions } = that.state;
    const { applicationId } = that.props;
    that.props.form.validateFields((errors, values) => {
      if (!errors) {
        if (!imgUrl) {
          that.setState({
            isImgOk: false
          })
          return false
        };
        const hotQuestionList = [];
        for (const item of questions) {
          if(item.type == -1){
            hotQuestionList.push({ qaId: item.id, qaType: item.type,question:item.basicQuestion });
          }else{
            hotQuestionList.push({ qaId: item.id, qaType: item.type });
          }
        };
        const userTypeIdList = values.userType ? values.userType : [];
        let obj = {
          name: values.labelName,
          imgUrl,
          imgName,
          applicationId,
          userTypeIdList: userTypeIdList.indexOf('all') > -1 ? [] : userTypeIdList,
          hotQuestionList,
        };
        that.doSubmitFetch(obj);
      }
    });
  };

  /* 保存/编辑请求标签基础信息 */
  doSubmitFetch = obj => {
    const that = this;
    const { detail } = that.state;
    that.setState({ submitLoading: true }, async () => {
      let res = {};
      if (detail) {
        /* 编辑 */
        obj.id = detail.id;
        res = await fetchEditLabel(obj);
      } else {
        /* 保存 */
        res = await fetchAddLabel(obj);
      }

      message.info(res.msg);
      that.setState({ submitLoading: false }, () => {
        that.cancelModal();
        that.props.refreshTableList();
      });
    });
  };

  addSelfQuestion = () => {
    const { questions } = this.state;
    questions.push({
      id:"",
      basicQuestion:"",
      type:-1,
      qaType:-1
    })
    this.setState({questions})
  }

  doChangeQuestion = (e,index) => {
    const { questions } = this.state;
    let newQuestions = []
    for(let i in questions){
      if(questions[i].type == -1 && i == index){
        questions[i].basicQuestion = e.target.value
      }

      newQuestions.push(questions[i])
    }

    this.setState({
      questions:newQuestions
    })
  }

  setImgUrl = imgUrl => {
    this.props.form.setFieldsValue({img:imgUrl})
    this.setState({
      imgUrl
    })
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { applicationId, userList } = this.props;
    const { visible, imgUrl, questions, userTypeChecks, isImgOk,defaultImgUrl } = this.state;
    const renderType = type => {
      let txt = '';
      switch (type) {
        case -1:
          txt = formatMessage({ id: 'hotSpots.editModal.custom' });
          break;
        case 1:
          txt = formatMessage({ id: 'hotSpots.editModal.qna' });
          break;
        case 2:
          txt = formatMessage({ id: 'hotSpots.editModal.mindMap' });
          break;
        case 3:
          txt = formatMessage({ id: 'hotSpots.editModal.multipleRounds' });
          break;
        case 4:
          txt = formatMessage({ id: 'hotSpots.editModal.form' });
          break;
      }
      return txt;
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };

    return (
      <div>
        <Drawer title={formatMessage({ id: 'hotSpots.editModal.add' })} visible={visible} width={650} onClose={this.cancelModal}>
          <div>
            <h4 className={styles.hTitle}>{formatMessage({ id: 'hotSpots.editModal.basicInfo' })}</h4>
          </div>
          <Form {...formItemLayout}>
            <Form.Item label={formatMessage({ id: 'hotSpots.editModal.categoryLabel' })}>
              {getFieldDecorator('labelName', {
                rules: [
                  { required: true, message: formatMessage({ id: 'hotSpots.editModal.pleaseFillCategoryLabel' }),}
                ],
              })(<Input />)}
            </Form.Item>
            <Form.Item label={'图片'}>
              <div style={{display:"flex",flexWrap:"wrap",marginBottom:10}}>
                {defaultImgUrl && defaultImgUrl.length > 0 && defaultImgUrl.map((j, k) => {
                  return (
                      <div
                          key={k}
                          className={`${styles['default-img-li']} ${imgUrl === j.url ? styles['default-img-li-active'] : ''}`}
                          onClick={() => this.setImgUrl(j.url)}
                      >
                          <img src={j.url} width="36" height="36" />
                      </div>
                  )
                })}
              </div>
              {getFieldDecorator('img', {
                rules: [
                  { required: true, message: formatMessage({ id: 'hotSpots.editModal.pleaseUploadImage' }),}
                ]
              })(
                <Upload
                  name="file"
                  listType="picture"
                  className="avatar-uploader"
                  showUploadList={false}
                  action="/cloud/file/upload"
                  beforeUpload={this.beforeUpload}
                  onChange={this.handleChangeImage}
                  accept=".png,.jpg,.jpeg,.gif,.bmp,.tif,.ico,.webp"
                >
                  {imgUrl ? (
                    <img src={imgUrl} style={{ width: 50, height: 50, marginRight: 10 }} />
                  ) : (
                    ''
                  )}
                  <Button>{imgUrl ? formatMessage({ id: 'hotSpots.editModal.reupload' }) : formatMessage({ id: 'hotSpots.editModal.uploadImage' })}</Button>
                </Upload>
              )}
              {
                isImgOk ? '' : <div className="ant-form-explain" style={{ color: '#f5222d' }}>请上传图片</div>
              }
            </Form.Item>
          </Form>

          <div className={'clearfix'}>
            <h4 className={styles.hTitle} style={{ float: 'left', width: '50%' }}>
              {formatMessage({ id: 'hotSpots.editModal.hotQuestions' })}
            </h4>
            <Button type={'primary'} size={'small'} style={{ float: 'right' }} onClick={this.addSelfQuestion}>{formatMessage({ id: 'hotSpots.editModal.addCustom' })}</Button>
            <Button type={'primary'} size={'small'} style={{ float: 'right',marginRight:10 }} onClick={this.addHotQuestion}>{formatMessage({ id: 'hotSpots.editModal.addRelatedQuestion' })}</Button>
          </div>
          <div style={{ marginBottom: 40 }}>
            {questions.map((item, index) => {
              return (
                <div key={index} className={styles.hotBox}>
                  <div className={styles.hotPrefix}>{renderType(item.type)}</div>
                  {
                    item.type == -1 ? (
                      <Input className={styles.hotItem} style={{minHeight:'40px',lineHeight:'40px',border:"none"}} value={item.basicQuestion} onChange={e => this.doChangeQuestion(e,index)} />
                    ) : (
                      <div className={styles.hotItem} style={{ paddingRight: 60, position: 'relative' }}>
                        {item.basicQuestion}
                      </div>
                    )
                  }
                  
                  <img
                    src={close}
                    className={styles.hotOption}
                    onClick={() => this.removeQuestion(item,index)}
                  />
                  {index != 0 ? (
                    <img
                      src={top}
                      className={styles.hotOption}
                      onClick={() => this.moveQuestion(index, 'up')}
                    />
                  ) : (
                    ''
                  )}
                  {index != questions.length - 1 ? (
                    <img
                      src={bottom}
                      className={styles.hotOption}
                      onClick={() => this.moveQuestion(index, 'down')}
                    />
                  ) : (
                    ''
                  )}
                </div>
              );
            })}
          </div>

          <div
            style={{
              position: 'absolute',
              right: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'right',
            }}
          >
            <Button onClick={this.cancelModal} style={{ marginRight: 8 }}>{formatMessage({ id: 'hotSpots.editModal.cancel' })}</Button>
            <Button onClick={this.doSubmitForm} type="primary">{formatMessage({ id: 'hotSpots.editModal.confirm' })}</Button>
          </div>
        </Drawer>

        
        <RelatedKnowledgeV2 
          onRef={ref => this.RelatedKnowledge = ref}
          applicationId={applicationId}
          chooseType='mutiple'
          getRelatedList={this.addQuestionByHot}
        />
      </div>
    );
  }
}

export default Form.create()(EditModal);
